/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:09:46
 * @Last Modified by: 张笑天
 * @Last Modified time: 2018-03-07 17:09:46
 */
import React from 'react';
import classNames from 'classnames';

export default class Switch extends React.Component {
  static displayName = 'NewSwitch';
  constructor(props) {
    super(props);
    this.isInstanceMounted = false;
    this.prefixClass = 'wea-email-switch';
    this.state = {
      checked: props.checked || 0,
    };
  }
  componentDidMount() {
    this.isInstanceMounted = true;
  }
  componentWillReceiveProps(nextProps) {
    const { checked: _checked } = this.state;
    const { checked } = nextProps;
    checked !== _checked && this.setState({ checked });
  }
  componentWillUnmount() {
    this.isInstanceMounted = false;
  }
  onChange(checked) {
    const { onChange } = this.props;
    this.setState({ checked });
    typeof onChange === 'function' && onChange(checked);
  }
  render() {
    const { labels = [] } = this.props;
    const { checked } = this.state;
    return (
      <div className={this.prefixClass}>
        {
          labels.map(l => <span className={`${this.prefixClass}-label`}>{l}</span>)
        }
        <div className={`${this.prefixClass}-slide`}
          style={checked === 0
            ? { left: -1, marginRight: -5, right: '50%' }
            : { left: '50%', marginLeft: -5, right: -1 }
          }
        >
          {labels[checked]}
        </div>
        <div className={`${this.prefixClass}-labels`}>
        {
          labels.map((l, i) =>
            (<span key={i}
              className={classNames({
                [`${this.prefixClass}-label`]: true,
                [`${this.prefixClass}-label-show`]: true,
                [`${this.prefixClass}-label-checked`]: i === checked,
              })}
              onClick={() => this.onChange(i)}
            >
              {l}
            </span>),
          )
        }
        </div>
      </div>
    );
  }
}
